package com.htbb.base.util;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import com.htbb.model.Mail;


@Service("mailService")
public class MailUtils {

	private static final Logger LOGGER = Logger.getLogger(MailUtils.class);

	@Autowired
	private JavaMailSenderImpl javaMailSenderImpl;

	/**
	 * 创建MimeMessage
	 * 
	 * @param mail
	 * @param mailBean
	 * @return
	 * @throws MessagingException
	 * @throws UnsupportedEncodingException
	 */
	public MimeMessage createMimeMessage(Mail mail) throws MessagingException, UnsupportedEncodingException {
		MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage();
		MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
		messageHelper.setFrom(mail.getFrom(), mail.getFromName());
		messageHelper.setSubject(mail.getSubject());
		messageHelper.setTo(mail.getToEmails());
		messageHelper.setText(mail.getContext(), true); // html: true
		if(StringUtils.isNotBlank(mail.getPath())){
			FileSystemResource file = new FileSystemResource(new File(mail.getPath()));
			
			messageHelper.addAttachment(MimeUtility.encodeWord(mail.getFileName()), file);
		}
		return mimeMessage;
	}

	public void sendMail(Mail mail) throws UnsupportedEncodingException, MessagingException {
		MimeMessage msg = createMimeMessage(mail);
		javaMailSenderImpl.send(msg);
	}

	/**
	 * 按照模版发送邮件
	 * @param mail 邮件
	 * @param map 需要替换的模版字段
	 * @param templet 模版
	 */
	public void sendMailTemplate(Mail mail, Map<String, Object> map, String templet) {
		LOGGER.debug("****************sendMailTemplate  mail:"+mail+"  templet:"+templet);
		Iterator<Entry<String, Object>> iterator = map.entrySet().iterator();
		while (iterator.hasNext()) {
			Map.Entry<String, Object> entry = iterator.next();
			Object key = entry.getKey();
			Object val = entry.getValue();
			templet = templet.replaceAll("#" + key.toString() + "#", val.toString());
		}
		mail.setContext(templet);
		try {
			sendMail(mail);
		} catch (UnsupportedEncodingException | MessagingException e) {
			LOGGER.error("发送邮件失败 email:" + mail.getToEmails());
		}
	}
}
